<?php
namespace App\Http\Controllers\Api;
use App\Models\Goods;
use App\Models\GoodsType;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class GoodsController extends Controller
{
    protected $model;
    protected $typeModel;
    public function __construct(Goods $goods ,GoodsType $goodsType)
    {
        $this->model = $goods;
        $this->typeModel = $goodsType;
    }
 
    public function getGoodsList(Request $request)
    { 
        $machine_id = $request->machineId;         
        $machine = DB::table('machines')->find($machine_id);
        if(!$machine->connected_at){
            return $this->freig('机器离线');
        }
        if(!$machine->expire_time){
            return $this->xpir('设备过期');
        }
        $machine = DB::table('freight_ways')->where('machine_id', $machine_id)->where('stock', '>', 0)->where('state', 1)->get();
        $merchantId = DB::table('machine_managers')->select('manager_id')->where('machine_id',$machine_id)->where('type',3)->first();  
        if(is_null($merchantId)){
            $merchantId = DB::table('machine_managers')->select('manager_id')->where('machine_id',$machine_id)->where('type',2)->first();
        }
        $operationId = DB::table('machine_managers')->select('manager_id')->where('machine_id',$machine_id)->where('type',4)->first();
        if($machine){
            $machine = $machine->map(function($item, $key)use($merchantId,$operationId){
                $item->merchantId = $merchantId?$merchantId->manager_id:0;
                $item->operationId = $operationId?$operationId->manager_id:0;
                if($item->goods_id){
                    $goods = DB::table('goods')->where('id', $item->goods_id)->first();
                    if ($goods) {
                        $item->goods = array(
                            'goodsId' => $goods->id,
                            'goodsName' => $goods->goods_name,
                            'goodsImage' => ($goods->domainName).($goods->goods_image),
                            'merchantId' => $goods->merchant_id,
                            'machineId' => $item->machine_id,
                            'goodsUnit' => goods_unit($goods->goods_unit),
                            'mainboradNo' => $item->No
                        );
                    }
                }else{
                    $item->goods = null;
                }
                return $item;
            });            
        }
        return $this->success($machine);
    }
}
